<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { usePagination, useSwitchable } from '@/utils/hooks'
import { handleApi } from '@/utils/alert'
import { message, TableColumnType } from 'ant-design-vue'
import type { TableProps } from 'ant-design-vue'
import QueryForm from './supporter-waybill-template-form.vue'
import { deleteUserTemplate, getUserWaybillTemplates, setDefault, updateCustomTemplate } from "@/api/waybill.ts";
import CreateWaybillForm from "#/supporter-waybill-template/create-waybill-form.vue";
import TemplateEditor, { TemplateEditorProps } from "@/components/template-editor.vue";


const { dataSource, pagination, fetch, params, loading } = usePagination(getUserWaybillTemplates, handleApi)
// 创建表单模态框
const { state: modalState, on, off } = useSwitchable()
// 编辑模板模态框
const { state: editorModalState, on: openEditor, off: closeEditor } = useSwitchable()
// 预览模板模态框
const { state: previewModalState, on: openPreviewModal, off: closePreviewModal } = useSwitchable()

const columns: (TableColumnType & DataIndex<IUserWaybillTemplate>)[] = [
  { key: 'title', dataIndex: 'title', title: '快递模板名称' },
  { key: 'preview', title: '预览图' },
  { key: 'wp_code', dataIndex: 'wp_code', title: '快递编号' },
  { key: 'account', title: '电子面单账号' },
  { key: 'opt', title: '操作' }
]

const onTableChange: TableProps['onChange'] = (pg) => {
  params.value.page = pg.current
  params.value.pagesize = pg.pageSize
  fetch()
}

onMounted(() => {
  fetch()
})

const onFormSubmit = (p: any) => {
  params.value = {
    ...p,
    page: params.value.page,
    pagesize: params.value.pagesize
  }
  fetch()
}

const onFormButton = () => {
  on()
}

// 修复在 Table 组件下 record 类型无法推断的问题
const getRow = (row: IUserWaybillTemplate) => row
const getAddress = (row: IUserWaybillTemplate) => {
  return (row.province || '') +
    (row.city || '') +
    (row.district || '') +
    (row.detail || '')
}

const onCreateSuccess = () => {
  fetch()
  off()
}

const onDelConfirmed = async (id: number) => {
  loading.value = true
  const res = await deleteUserTemplate(id).catch(handleApi)
  if (res && res.code === 1) {
    message.success('删除成功')
    fetch()
  }
  loading.value = false
}

const onDefConfirmed = async (id: number) => {
  loading.value = true
  const res = await setDefault(id).catch(handleApi)
  if (res && res.code === 1) {
    message.success('修改成功')
    dataSource.value = dataSource.value?.map(i => ({ ...i, is_default: i.id === id ? 1 : 2 }))
  }
  loading.value = false
}

const editorProps = ref<TemplateEditorProps>()
const editingRecord = ref<IUserWaybillTemplate>()

const editTpl = (item: IUserWaybillTemplate, preview = false) => {
  console.log(item,'item')
  editingRecord.value = item
  const { template_extend, extend, standard_perview_url, standard_perview_bottom_url } = item

  if (!template_extend) {
    message.error('标准模板信息异常, 无法编辑或预览, 请联系管理员')
    return
  }
  const templateExtend: TemplateExtend = JSON.parse(template_extend)
  editorProps.value = {
    fields: [],
    img: standard_perview_url,
    botImg: standard_perview_bottom_url,
    paperWidth: templateExtend.default_config.body_width,
    paperHeight: templateExtend.default_config.body_height,
    customAreaWidth: templateExtend.default_config.custom_area_width,
    customAreaHeight: templateExtend.default_config.custom_area_height,
    customAreaLeft: templateExtend.default_config.custom_area_left,
    customAreaTop: templateExtend.default_config.custom_area_top
  }
  if (extend) {
    const fields: { config?: CustomTemplateFieldDetail[] } = JSON.parse(extend)
    if (editorProps.value && fields?.config) {
      editorProps.value.fields = fields.config
    }
  }

  if (preview)
    openPreviewModal()
  else
    openEditor()
}

const onEditorSave = async (fields: CustomTemplateFieldDetail[], url: string, _template: string) => {

  let str = '<text id="&id" left="&left" top="&top" width="&width" height="&height" presentation="$presentation" style="overflow: hidden;zIndex: 1;fontColor: #000000;alpha: 255;valign: top;fontFamily: &fontFamily;fontSize: &fontSize;fontWeight: normal;rotation: 0;"><![CDATA[ <% for(var i=0;i<(_data.items?.length);i++){ %><%=_data.items[i].itemName%><%=_data.items[i].itemSpecs%><%=_data.items[i].itemId%><%=_data.items[i].itemQuantity%><%}%> ]]></text>'
  let data = []
  fields.map(item=>{
    let obj = {
      code: item.field_name,
      name: item.text,
      value: str.replace('&id',item.field_name).replace('&left',item.left).replace('&width',item.width).replace('&top',item.top).replace('&height',item.height).replace('&$presentation',item.text).replace('&fontFamily',item.font_family).replace('&fontSize',item.font_size)
    }
    data.push(obj)
  })
  const res = await updateCustomTemplate({
    url,
    template_id: editingRecord.value!.id,
    extend: JSON.stringify(fields),
    data
  }).catch(handleApi)
  if (res && res.code === 1) {
    message.success('修改成功')
    closeEditor()
    await fetch()
  }
}

</script>


<template>
  <div class="px-4 py-8">
    <QueryForm @submit="onFormSubmit" @button="onFormButton"></QueryForm>
  </div>

  <ATable
    :columns="columns"
    :data-source="dataSource"
    :loading="loading"
    :pagination="pagination"
    @change="onTableChange"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'preview'">
        <AImage
          class="cursor-pointer"
          :src="getRow(record).standard_perview_url"
          :height="120"
          :preview="false"
          @click="editTpl(record, true)"
        ></AImage>
      </template>

      <template v-if="column.key === 'account'">
        <div class="flex flex-col">
          <span>授权账号: {{ getRow(record).acount_id }}</span>
          <span>网点名称: {{ getRow(record).branch_name }}</span>
          <span>网点地址: {{ getAddress(record) }}</span>
          <span>单号余额: {{ getRow(record).quantity }}</span>
        </div>
      </template>

      <template v-if="column.key === 'opt'">
        <div class="flex flex-col space-y-2 w-fit">
          <APopconfirm
            title="确定要将该模板设为默认模板吗?"
            ok-text="确定"
            cancel-text="取消"
            @confirm="() => onDefConfirmed(record.id)"
          >
            <AButton type="link" size="small" :disabled="getRow(record).is_default === 1">设为默认</AButton>
          </APopconfirm>

          <AButton type="link" size="small" @click="editTpl(record)">编辑</AButton>

          <APopconfirm
            title="确定要删除吗?"
            ok-text="确定"
            cancel-text="取消"
            @confirm="() => onDelConfirmed(record.id)"
          >
            <AButton type="link" size="small" danger>删除</AButton>
          </APopconfirm>
        </div>
      </template>
    </template>
  </ATable>

  <AModal v-model:open="modalState" :footer="null" title="添加快递模板" width="800px">
    <CreateWaybillForm @success="onCreateSuccess" @cancel="off"></CreateWaybillForm>
  </AModal>

  <AModal v-model:open="editorModalState" :footer="null" :title="null" width="800px" destroy-on-close>
    <div class="h-[700px] w-full">
      <TemplateEditor v-if="editorProps" v-bind="editorProps" @save="onEditorSave" @cancel="closeEditor"></TemplateEditor>
    </div>
  </AModal>

  <div
    v-if="previewModalState && editorProps"
    class="absolute top-0 left-0 w-screen h-screen bg-opacity-70 bg-gray-800 flex items-center justify-center"
    @click.self="closePreviewModal"
  >
    <div class="h-screen max-w-[500px] bg-white relative left-[-200px]">
      <TemplateEditor v-bind="editorProps" readonly></TemplateEditor>
    </div>
  </div>
</template>
